package com.semanticweb.webapp.model.ontology;

import org.apache.lucene.document.Document;

import com.semanticweb.webapp.ontology.CIDOC;
import com.semanticweb.webapp.ontology.CType;
import com.semanticweb.webapp.ontology.Ont;
import com.semanticweb.webapp.ontology.OntHelper;
import com.semanticweb.webapp.ontology.Query;
import com.semanticweb.webapp.search.IDocument;
import com.semanticweb.webapp.search.SearchMD;

/**
 * Class which represents 'Invetarni broj' from the chart.
 * 
 * @author Lab
 * 
 */
public class InventaryNumber extends DefaultAbstractEntity<String> implements IDocument {

    public static final String ONT_IDENTIFIER = "id";

    public InventaryNumber(final String id) {
        super(id);
    }

    @Override
    public void toRDF() {
        OntHelper.toRDFValueWithType(this.id, CIDOC.P48, CIDOC.E42, this.value, Ont.formatURIPart(ONT_IDENTIFIER),
                CType.INVENTARY_NUMBER);
    }

    public void fromRDF() {
        this.value = OntHelper.fromRDFValueWithType(this.id, CIDOC.P48, CIDOC.E42, CType.INVENTARY_NUMBER);
    }

    public static boolean inventaryNumberExists(final String inventaryNumber) {
        final Query q = new Query();
        return q.ask().label("in", inventaryNumber).type("in", CIDOC.E42.queryValue())
                .connect("in", CIDOC.P2.queryValue(), CType.INVENTARY_NUMBER.queryValue()).check();
    }

    public static String findID(final String inventaryNumber) {
        final Query q = new Query();
        final String[] result = q.select("item").type("in", CIDOC.E42.queryValue()).label("in", inventaryNumber)
                .connect("in", CIDOC.P2.queryValue(), CType.INVENTARY_NUMBER.queryValue())
                .type("item", CIDOC.E22.queryValue()).connect("item", CIDOC.P48.queryValue(), "in").find();

        if (result.length < 1) {
            return null;
        }

        return Ont.isolateURISuffix(result[0]);
    }

    @Override
    public void toIndexDocument(final Document doc) {
        if (this.value != null) {
            doc.add(SearchMD.INVENTARY_NUMBER.createField(this.value));
            doc.add(SearchMD.CONTENT.createField(this.value));
        }
    }
}
